#include <xp/bas/string.h>
#include <xp/bas/stdio.h>
#include <xp/bas/sysapi.h>
#include <xp/bas/locale.h>
#include <dirent.h>

int xp_main (int argc, xp_char_t* argv[])
{
	DIR* dp;
	struct dirent* ent;
	xp_char_t buf[XP_PATH_MAX + 1];
	xp_size_t len;
	xp_mchar_t path_mb[XP_PATH_MAX + 1];
	int flags;
	
	xp_setlocale ();

	if (argc != 3) {
		xp_fprintf (xp_stderr, 
			XP_TEXT("usage: %s directory pattern\n"), argv[0]);
		return -1;
	}
	
	xp_wcstomcs_strict (argv[1], path_mb, xp_countof(path_mb));
	dp = opendir (path_mb);
	if (dp == XP_NULL) {
		xp_fprintf (xp_stderr, XP_TEXT("cannot open %s\n"), argv[1]);
		return -1;
	}

	flags = XP_STRFNMAT_PATHNAME | XP_STRFNMAT_PERIOD;

	while ((ent = readdir (dp)) != XP_NULL) {
		len = xp_strxapp (buf, 
			xp_countof(buf), argv[1], XP_TEXT("/"), XP_NULL);
		xp_mcstowcs (ent->d_name, &buf[len], xp_countof(buf) - len);

		len = xp_strlen (buf);
		buf[len] = 'a';
		if (xp_strxnfnmat (buf, len, argv[2], xp_strlen(argv[2]), flags))  {
			buf[len] = 0;
			xp_printf (XP_TEXT("%s\n"), buf);
		}

	}
	
	closedir (dp);

	return 0;
}
